package com.wpml.netty.reactor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Description
 * @Date 2021-07-16
 * @Author wangpei
 **/
public class SelectorTest {

    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();


        ServerSocketChannel server = ServerSocketChannel.open();
        server.configureBlocking(false);
        server.bind(new InetSocketAddress(8888));

        server.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            System.out.println("before select ..." + selector.keys().size());
            int num = selector.select();
            System.out.println("after select ..." + selector.keys().size());
            if (num > 0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                        SocketChannel client = ssc.accept();
                        System.out.println("client connect ..." + client.getRemoteAddress() + " ");
                    }
                }
            }
        }
    }
}
